package logic

import (
	"context"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"week1/ordersrv/models"
	"week1/ordersrv/service"

	"week1/ordersrv/internal/svc"
	"week1/ordersrv/ordersrv"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *ordersrv.CreateOrderReq) (*ordersrv.CreateOrderRes, error) {
	// todo: add your logic here and delete this line
	//添加订单商品
	var (
		tx         = models.DB.Begin()
		orderSn    = uuid.NewString()
		orderTotal float64
	)
	for _, v := range in.GoodsDetailInfo {
		//查询商品单价
		goods, err := service.GetGoodsById(uint(v.GoodId))
		if err != nil {
			tx.Rollback()
			return nil, err
		}
		item, err := service.CreateOrderItem(tx, &models.OrderItems{
			OrderSn:    orderSn,
			GoodId:     int(v.GoodId),
			GoodsStock: int(v.GoodNum),
			GoodsPrice: goods.GoodsPrice,
		})
		if err != nil {
			tx.Rollback()
			return nil, err
		}
		orderTotal += float64(v.GoodNum) * item.GoodsPrice
	}
	//生成订单
	order, err := service.CreateOrder(tx, &models.Order{
		Model:          gorm.Model{},
		OrderSn:        orderSn,
		UserId:         int(in.Userid),
		OrderTotal:     orderTotal,
		OrderAddressId: uint(in.OrderAddressId),
	})
	if err != nil {
		tx.Rollback()
		return nil, err
	}
	tx.Commit()
	return &ordersrv.CreateOrderRes{OrderSn: order.OrderSn}, nil
}
